import React, { useMemo, useState } from 'react';
import { useLocation, useHistory } from 'react-router-dom';
import { Button, Input, Space, message } from 'antd';
import { LeftOutlined } from '@ant-design/icons';
import { createIntention, modifyIntention } from 'admin/servers/servers';
import qs from 'query-string';

import './style.scss';
import ExtendQuestion from '../extendQuestion';

/**电信特殊需求-表格-展示扩展问题列表 */
const Actions: React.FC = () => {
  // 路由location
  const location = useLocation();
  // URL查询字符串=>对象
  const query = useMemo(() => {
    return qs.parse(location.search);
  }, [location.search]);
  const versionId = Number(query.versionId);
  const history = useHistory();

  // 意图名称 新增/编辑公用
  const [intentionName, setIntentionName] = useState<string>(
    query.intentionName
      ? decodeURIComponent((query.intentionName as string).replace(/%/g, '%25'))
      : ''
  );

  // 保存按钮loading
  const [saveLoading, setSaveLoading] = useState<boolean>(false);

  // 保存按钮-是否可用
  const [saveDisable, setSaveDisable] = useState(false);

  // 意图ID
  const [intentionId, setIntentionId] = useState<number>(
    query.intentionId ? Number(query.intentionId) : 0
  );

  /**
   * 请求创建意图接口
   */
  const requestCreateIntention = async () => {
    setSaveLoading(true);
    try {
      const res = await createIntention({
        intentionName: intentionName.trim(),
        versionId,
      });
      if (res.code === 0) {
        message.success('新增意图成功');
        // 新增完，保存id,继续编辑意图
        const newId = res.data.intentionId;
        setIntentionId(newId);
        // 替换路由
        history.replace(
          `/webapp/outbound/ai/robots/version/flow/actions?versionId=${versionId}&intentionId=${newId}&intentionName=${encodeURIComponent(
            intentionName
          )}`
        );
      } else {
        message.error(`${res.tips}(错误码: ${res.code})`);
      }
      console.log('createIntention -> res', res);
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    setSaveLoading(false);
  };

  /**
   * 请求编辑意图接口
   */
  const requestModifyIntention = async () => {
    setSaveLoading(true);
    try {
      const res = await modifyIntention({
        intentionName: intentionName.trim(),
        intentionId,
      });
      if (res.code === 0) {
        message.success('编辑意图成功');
      } else {
        message.error(`${res.tips}(错误码: ${res.code})`);
      }
      console.log('modifyIntention -> res', res);
      // 替换路由
      history.replace(
        `/webapp/outbound/ai/robots/version/flow/actions?versionId=${versionId}&intentionId=${intentionId}&intentionName=${encodeURIComponent(
          intentionName
        )}`
      );
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    setSaveLoading(false);
  };

  /**
   * 点击保存意图按钮
   */
  const saveIntentionName = () => {
    if (!intentionName.trim()) {
      message.warning('意图名称不能为空！');
      return;
    }
    console.log(intentionName);
    if (!intentionId) {
      requestCreateIntention();
    } else {
      requestModifyIntention();
    }
  };

  // 保存按钮：启用、禁用
  function updateSave(val: boolean) {
    setSaveDisable(val);
  }

  return (
    <>
      <div className="nav">
        <Button
          type="link"
          onClick={() => {
            history.goBack();
          }}
        >
          <LeftOutlined />
          返回
        </Button>
        <div className="title">{intentionId ? '编辑意图' : '新建意图'}</div>
      </div>
      <div className="intention-head">
        <Space size="large">
          <div>
            <span style={{ color: '#ff0000' }}>*</span>意图名称
          </div>
          <Input
            placeholder="请输入20位以内字数"
            style={{ width: 300 }}
            maxLength={20}
            value={intentionName}
            onChange={e => setIntentionName(e.currentTarget.value)}
          />
          <Button
            type="primary"
            loading={saveLoading}
            onClick={saveIntentionName}
            disabled={saveDisable}
          >
            保存
          </Button>
          <Button
            onClick={() => {
              history.goBack();
            }}
          >
            取消
          </Button>
        </Space>
      </div>
      <ExtendQuestion intentionId={intentionId} mode="intention" fn={updateSave} />
    </>
  );
};

export default Actions;
